package com.fucking.great.context.config;

import cn.hutool.core.util.StrUtil;
import com.fucking.great.context.plun.Plug;
import com.fucking.great.context.plun.PlugFactory;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

public abstract class BaseTxnConfiger implements TxnConfiger{
    private static final Map<String,PlugFactory> PLUG_FACTORY_MAP = new ConcurrentHashMap<>();
    public BaseTxnConfiger(){
        registerPlugFactory();
    };

    protected void registerPlugFactory(){
        if (PLUG_FACTORY_MAP.size() == 0){
            ServiceLoader<PlugFactory> peoples = ServiceLoader.load(PlugFactory.class);
            Iterator<PlugFactory> iterator = peoples.iterator();
            while (iterator.hasNext()) {
                PlugFactory plugFactory = iterator.next();
                // 放入并校验。
                String name = plugFactory.name();
                if (this.PLUG_FACTORY_MAP.putIfAbsent(name, plugFactory) != null) {
                    throw new ExceptionInInitializerError(StrUtil.format(
                            "name=[{}],current plugFactoryClass=[{}] exist , please pom or jar for plugFactory ",
                            name ,plugFactory.getClass()));
                }
            }
        }
    }

    @Override
    public Plug getPlug(String name, String systemName) {
        // 从注册列表中获得
        PlugFactory plugFactory = this.PLUG_FACTORY_MAP.get(name);
        // 获得配置
        SystemConfigBean systemConfigBean = this.getSystemConfigBean(systemName);
        Map<String, String> config = systemConfigBean.getConfig();
        // 初始化
        Plug plug = null;
        if(plugFactory !=null){
            plug = plugFactory.initPlug(config);
        }
        //
        return plug;
    }

    @Override
    public final Collection<PlugFactory> getAllPlugFactory() {
        return PLUG_FACTORY_MAP.values();
    }
}
